package com.uzhie.spring;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import org.apache.log4j.Logger;

import javax.servlet.ReadListener;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.nio.CharBuffer;

/**
 * Created by TangFei on 2018/7/21.
 * httpRequest 包装类
 */
public class HttpServletRequestWrapper extends javax.servlet.http.HttpServletRequestWrapper {

    private Logger logger = Logger.getLogger(this.getClass());
    private final JSONObject requestJSON;

    public JSONObject getRequestJSON() {
        return requestJSON;
    }

    public HttpServletRequestWrapper(HttpServletRequest httpServletRequest) throws IOException {
        super(httpServletRequest);
        BufferedReader reader = httpServletRequest.getReader();
        CharBuffer charBuffer = CharBuffer.allocate(httpServletRequest.getContentLength());
        reader.read(charBuffer);
        this.requestJSON = JSONObject.parseObject(charBuffer.array(), httpServletRequest.getContentLength(), JSONObject.class, Feature.AllowArbitraryCommas);
        logger.info("请求体：" + requestJSON);
    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(getInputStream()));
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        final ByteArrayInputStream bais = new ByteArrayInputStream(requestJSON.toJSONString().getBytes());
        return new ServletInputStream(bais);
    }

    private class ServletInputStream extends javax.servlet.ServletInputStream {

        private InputStream inputStream;

        public ServletInputStream(InputStream inputStream) {
            this.inputStream = inputStream;
        }

        @Override
        public boolean isFinished() {
            return false;
        }

        @Override
        public boolean isReady() {
            return false;
        }

        @Override
        public void setReadListener(ReadListener readListener) {

        }

        @Override
        public int read() throws IOException {
            return inputStream.read();
        }
    }
}
